<?php

namespace MoChat\App\Client\Service;

use Hyperf\DbConnection\Db;
use MoChat\App\Client\Contract\ClientTagPivotContract;
use MoChat\App\Client\Model\ClientTagPivot;
use MoChat\Framework\Service\AbstractService;

class ClientTagPivotService extends AbstractService implements ClientTagPivotContract
{
    /**
     * @var ClientTagPivot
     */
    protected $model;

    /**
     * 删除 - 多条 根据标签id.
     * @return int 删除条数
     */
    public function deleteWorkContactTagPivotsByTagId(array $tagId): int
    {
        return $this->model::query()
            ->whereIn('client_tag_id', $tagId)
            ->delete();
    }

    /**
     * 查询多条 - 根据客户id
     * @param int $clientId 客户id
     * @param array $columns 查询字段
     * @return array 数组
     */
    public function getClientTagPivotsByOtherId($clientId, array $columns = ['*']): array
    {
        $res = $this->model::query()
            ->where('client_id', $clientId)
            ->get($columns);
        if (empty($res)) {
            return [];
        }
        return $res->toArray();
    }

    public function getAllClientTagPivotByIds($ids, array $filed = ['*']): array
    {
        $data = $this->model->whereIn('client_id', $ids)->select($filed)->get();
        return empty($data) ? [] : $data->toArray();
    }


    /**
     * 获取同一个标签的客户数标签
     * @param $clientIds
     * @param $tagIds
     * @return array
     */
    public function getTagGroupsByClientIds($clientIds, $tagIds): array
    {
        $list = $this->model->whereIn('client_id', $clientIds)
            ->whereIn('client_tag_id', $tagIds)
            ->select([
                Db::raw('COUNT(*) as count'),
                'client_tag_id',
                Db::raw('GROUP_CONCAT(DISTINCT client_id SEPARATOR ",") AS client_ids'),//客户id
            ])
            ->groupBy([
                'client_tag_id'
            ])->get();
        return empty($list) ? [] : array_column($list->toArray(), null, 'clientTagId');
    }
}